/*
 * UMLSynch plugin for Eclipse
 * http://umlsynch.googlecode.com
 *
 * Copyright 2008-2010, Evgeny Alexeyev
 * Licensed under the EPL - v1.0
 * http://www.eclipse.org/legal/epl-v10.html
 *
 */

package com.googlecode.umlsynch.eclipse.rpc;

import com.googlecode.umlsynch.rpc.TEditorRpcDispatcher;
import com.googlecode.umlsynch.rpc.TFinderRpcDispatcher;
import com.googlecode.umlsynch.rpc.TIndexerRpcDispatcher;
import com.googlecode.umlsynch.rpc.base.IDebug;
import com.googlecode.umlsynch.rpc.base.TConfig;
import com.googlecode.umlsynch.rpc.base.TDebug;
import com.googlecode.umlsynch.rpc.base.TDispatcherManager;
import com.googlecode.umlsynch.rpc.base.TIOHandler;

public class Server {
	private TConfig cfg;
	private TDispatcherManager dm;
	private Thread thread;
	private TDebug debug;
	public boolean activatedFlag = false;

	public TEditorRpcImplementation erpc;
	public TFinderRpcImplementation frpc;
	public TIndexerRpcImplementation irpc;

	public Server (TConfig eclipse, IDebug dbg) {
		debug = new TDebug(dbg);
		dm = new TDispatcherManager(debug);
		cfg = eclipse;
		 

		if (thread == null) {
			thread = new Thread() {
				public void run() {
					// Editor interface implementation
					erpc = new TEditorRpcImplementation(debug);
					// Editor interface dispatching
					TEditorRpcDispatcher erpcd = new TEditorRpcDispatcher(debug, dm, erpc);

					// Finder interface implementation
					frpc = new TFinderRpcImplementation(debug);
					// Finder interface dispatcher
					TFinderRpcDispatcher frpcd = new TFinderRpcDispatcher(debug,dm, frpc);

					// Indexer-access interface implementation
					irpc = new TIndexerRpcImplementation(debug);
					TIndexerRpcDispatcher irpcd = new TIndexerRpcDispatcher(debug,dm, irpc);
					
					// May be it was not a good idea to 
					// porvide DiagramManager as argument
					// because now I can see warnings about unused variables

					// Handling of input/output 
					TIOHandler ioh = new TIOHandler(cfg, debug);
					
					// Create Server Socket
					if (!ioh.ServerConnect()) {
						debug.Error("Failed to open server socket");
						activatedFlag = true;
						return;
					}
					// Server socket activated- flag 
					activatedFlag = true;
					
					// loop an accept-process cycle 
					// dm.process close socket on each iteration
					// it is allow to accept requests from different 
					// client:
					while (ioh.accept()) {
						dm.process(ioh);	
					}

					debug.Error("Exit from dispatcher manager thread");
				}
			};
			thread.start();
		}

	}
}
